<?php

/**
 * 功能描述：	文件上传/图片压缩（调用方法详细看尾部注释部分示例）
 * @module		UploadsFiles
 * @createdate	2020年04月10日
 * @version		V1.0
 * @author		ZhuHaili
 * @copyright	2020 zhl 版权所有
 */

class UploadsFiles{

    private $_sysFiles;
    private $_sysError;
    private $_sysFilePath;
    private $_sysFileSize;
    private $_sysFileType;
    private $_sysThumFlag;
    private $_sysThumWidth;
    private $_sysThumHeight;
    private $_sysThumQuality;
    private $_sysThumPath;
    private $_sysSuffix;
    private $_sysFileNewName;
    private $_sysFileNewPath;
    private $_sysFileVague;

    /**
     * UploadsFiles constructor
     */
    function __construct() {
        $fileType = 'jpg|jpeg|jpe|jpz|gif|png|wbmp|bmp|ai|psd|txt|doc|docx|pdf|chm|html|htm|xml|xls|xlsx|csv|ppt|pptx|';
        $fileType .= 'pps|ppsx|mp3|wav|wma|ra|mid|ogg|ape|mp4|m4v|wmv|rm|rmvb|mpg|mpeg|mpe|3gp|mov|avi|flv|zip|rar|7z|cab';
        $this->_sysError = $this->errorArr();
		$this->_sysFilePath = './uploads/'; // 文件上传默认路径
		$this->_sysFileSize = 2*1024*1024;  // 文件上传大小默认2Mb
		$this->_sysFileType = $fileType;    // 默认上传文件类型
        // 图片压缩规则类型：$this->_sysThumFlag
        // 0:不生成缩略图，1:原图压缩到指定宽高，2:宽度固定高度自适应，3:高度固定宽度自适应，4:以原图中心点截图，
        // 5:智能识别2或者3，6：宽度限制最大值高度自适应，7：高度限制最大值宽自适应，
        // 8:不超过设定按原图超过按照设定（限制最大宽和最大高），其他值均为1,
		$this->_sysThumFlag = 0;
        $this->_sysThumWidth = 100;     // 缩略图宽默认100像素
        $this->_sysThumHeight = 100;    // 缩略图高默认100像素
        $this->_sysThumQuality = 100;   // 缩略图质量90~100;
        $this->_sysThumPath = './uploads/thum/'; // 缩略图默认上传路径
        $this->_sysFileVague = false;   // 无后缀名的文件上传 true:支持，false:不支持(建议不开启,当前类型解析还不全)
    }

    /**
     * Notes: 上传文件
     * User: ZhuHaili
     * Date: 2020/4/10
     */
    public function uploadFile($params){
        // 为$_FILE时验证文件
        if(!isset($params['base64']) || !$params['base64']){
            $result = $this->verifyFile($params);
            if(!empty($result)){
                return $result;
            }
        }
        // 参数验证和赋值
        $result = $this->verifyParam($params);
        if(!empty($result)){
            return $result;
        }
        // 开始文件上传
        $result = array();
        // base64上传
        if(isset($params['base64']) && $params['base64']){
            if(is_array($params['base64'])){
                // 多文件
                foreach($params['base64'] as $k=>$data){
                    $result[] = $this->base64do($data);
                }
                return $result;
            }else{
                // 单文件
                return $this->base64do($params['base64']);
            }
        }else{
        // $_FILE上传
            if(is_array($this->_sysFiles['name']) && !empty($this->_sysFiles['name'])){
                // 多文件
                foreach($this->_sysFiles['name'] as $k=>$fileName){
                    $fileSize = $this->_sysFiles['size'][$k];
                    $fileTmp = $this->_sysFiles['tmp_name'][$k];
                    $result[] = $this->uploadsdo($fileName, $fileSize, $fileTmp);
                }
                return $result;
            }else{
                // 单文件
                return $this->uploadsdo($this->_sysFiles['name'], $this->_sysFiles['size'], $this->_sysFiles['tmp_name']);
            }
        }
    }

    /**
     * Notes: base64上传（目前只支持图片）
     * User: ZhuHaili
     * Date: 2020/4/10
     * @param $data
     * @return mixed
     */
    private function base64do($data){
        // 正则匹配填充搜索结果
        if(!preg_match('/^(data:\s*image\/(\w+);base64,)/', $data, $res)){
            return $this->_sysError[1];
        }
        $this->_sysSuffix = $res[2]; // 文件类型
        // 文件类型判断
        if(!in_array($this->_sysSuffix, explode('|',$this->_sysFileType))){
            return $this->_sysError[5];
        }
        // 拼接文件全路径
        $this->_sysFileNewName = $this->fileNameStr();
        $this->_sysFileNewPath = $this->_sysFilePath.$this->_sysFileNewName.'.'.$this->_sysSuffix;
        if(!file_put_contents($this->_sysFileNewPath, base64_decode(str_replace($res[1], '', $data)))){
            return $this->_sysError[3];
        }
        $fileInfo = $this->getFileInfo($this->_sysFileNewPath);
        $result = $this->_sysError[0];
        $result['data'] = $fileInfo;
        $result['data']['path'] = $this->_sysFileNewPath;
        $result['data']['type'] = $this->_sysSuffix;
        $thumInfo = $this->cutThum($fileInfo);
        if(!empty($thumInfo)){
            $result['code'] = $thumInfo['code'];
            $result['msg'] = $thumInfo['msg'];
            if(!empty($result['data'])){
                $result['data'] = array_merge($result['data'], $thumInfo['data']);
            }
        }
        return $result;
    }

    /**
     * Notes: 二进制上传文件执行
     * User: ZhuHaili
     * Date: 2020/4/10
     * @param $fileName
     * @param $fileSize
     * @param $fileTmp
     * @return mixed
     */
    private function uploadsdo($fileName, $fileSize, $fileTmp){
        if($fileSize > $this->_sysFileSize){
            return $this->_sysError[4];
        }
        $suffix = $this->getFileSuffix($fileName);
        if($suffix == 'JPG' && !$this->_sysFileVague){
            return $this->_sysError[5];
        }
        $this->_sysSuffix = $suffix;
        if(!in_array($suffix, explode('|',$this->_sysFileType))){
            return $this->_sysError[5];
        }
        $this->_sysFileNewName = $this->fileNameStr();
        $this->_sysFileNewPath = $this->_sysFilePath.$this->_sysFileNewName.'.'.$this->_sysSuffix;
        // 将上传的文件移动到新位置
        if(!move_uploaded_file($fileTmp, $this->_sysFileNewPath)){
            return $this->_sysError[8];
        }
        if($this->_sysSuffix == 'JPG'){
            $uploadSuffix = $this->getFileType();
            $this->_sysSuffix = $uploadSuffix;
            $updateFilePath = $this->_sysFilePath.$this->_sysFileNewName.'.'.$this->_sysSuffix;
            $re = rename($this->_sysFileNewPath, $updateFilePath);
            if(!$re){
                @unlink($this->_sysFileNewPath);
                return $this->_sysError[10];
            }
            $this->_sysFileNewPath = $updateFilePath;
        }
        $fileInfo = $this->getFileInfo($this->_sysFileNewPath);
        $result = $this->_sysError[0];
        $result['data'] = $fileInfo;
		$result['data']['name'] = $this->_sysFileNewName.'.'.$this->_sysSuffix;
        $result['data']['path'] = $this->_sysFileNewPath;
        $result['data']['type'] = $this->_sysSuffix;
        $thumInfo = $this->cutThum($fileInfo);
        if(!empty($thumInfo)){
            $result['code'] = $thumInfo['code'];
            $result['msg'] = $thumInfo['msg'];
            if(!empty($result['data'])){
                $result['data'] = array_merge($result['data'], $thumInfo['data']);
            }
        }
        return $result;
    }

    /**
     * Notes: 生成缩略图时基础设置
     * User: ZhuHaili
     * Date: 2022/11/7
     */
    private function thumBase($param){
        $this->_sysThumFlag = 1;
        if(isset($param['thum_flag'])){
            $thum_flag = intval($param['thum_flag']);
            $thum_flag = $thum_flag > 6 ? 1 : $thum_flag;
            $this->_sysThumFlag = $thum_flag;
        }
        $this->_sysThumWidth = 100;
        $this->_sysThumHeight = 100;
        if(isset($param['thum_width']) && intval($param['thum_width'])){
            $this->_sysThumWidth = intval($param['thum_width']);
        }
        if(isset($param['thum_height']) && intval($param['thum_height'])){
            $this->_sysThumHeight = intval($param['thum_height']);
        }
        if(isset($param['thum_path']) && $param['thum_path']){
            $res = $this->createPath($param['thum_path']);
            if(!$res){
                return $this->_sysError[7];
            }
            $this->_sysFilePath = $param['thum_path'];
            $this->_sysThumPath = $param['thum_path'];
        }
        if(isset($param['thum_quality']) && intval($param['thum_quality'])){
            $this->_sysThumQuality = intval($param['thum_quality']);
        }
        return false;
    }

    /**
     * Notes:创建缩略图
     * User: ZhuHaili
     * Date: 2022/11/7
     */
    public function createThum($param){
        // 本地图片上传
        if(isset($param['local']) && $param['local']){
            return $this->localThum($param);
        }
        // FILE上传
        if(isset($param['input']) && $param['input']){
            return $this->fileThum($param);
        }
        // base64上传
        if(isset($param['base64']) && $param['base64']){
            return $this->base64Thum($param);
        }
        return $this->_sysError[1];
    }

    /**
     * Notes:创建缩略图-根据base64
     * User: ZhuHaili
     * Date: 2022/11/7
     */
    private function base64Thum($param){
        $res = $this->thumBase($param);
        if($res){
            return $res;
        }
        $data = $param['base64'];
        // 正则匹配填充搜索结果
        if(!preg_match('/^(data:\s*image\/(\w+);base64,)/', $data, $res)){
            return $this->_sysError[1];
        }
        $this->_sysSuffix = $res[2]; // 文件类型
        // 文件类型判断
        if(!in_array($this->_sysSuffix, explode('|',$this->_sysFileType))){
            return $this->_sysError[5];
        }
        // 拼接文件全路径
        $this->_sysFileNewName = $this->fileNameStr();
        $this->_sysFileNewPath = $this->_sysFilePath.$this->_sysFileNewName.'.'.$this->_sysSuffix;
        if(!file_put_contents($this->_sysFileNewPath, base64_decode(str_replace($res[1], '', $data)))){
            return $this->_sysError[3];
        }
        $fileInfo = $this->getFileInfo($this->_sysFileNewPath);
        $result = $this->_sysError[0];
        $result['data'] = array();
        $thumInfo = $this->cutThum($fileInfo);
        if(!empty($thumInfo)){
            $result['code'] = $thumInfo['code'];
            $result['msg'] = $thumInfo['msg'];
            $result['data'] = $thumInfo['data'];
        }
        return $result;
    }

    /**
     * Notes:创建缩略图-根据FILE
     * User: ZhuHaili
     * Date: 2022/11/7
     */
    private function fileThum($param){
        if(!isset($param['input']) || !$param['input']){
            return $this->_sysError[1];
        }
        if(!isset($_FILES[$param['input']])){
            return $this->_sysError[1];
        }
        $res = $this->thumBase($param);
        if($res){
            return $res;
        }
        $thumKeep = isset($param['thum_keep']) ? $param['thum_keep'] : 0;
        $this->_sysFileNewName = !$thumKeep ? $this->fileNameStr() : $this->getFileSuffix($_FILES[$param['input']]['name'], PATHINFO_FILENAME);
        $this->_sysSuffix = $this->getFileSuffix($_FILES[$param['input']]['name']);
        $this->_sysFileNewPath = $_FILES[$param['input']]['tmp_name'];
        $imageData = @getimagesize($_FILES[$param['input']]['tmp_name']);
        $fileInfo['width'] = isset($imageData[0]) ? $imageData[0] : 0;
        $fileInfo['height'] = isset($imageData[1]) ? $imageData[1] : 0;
        $fileInfo['size'] = $_FILES[$param['input']]['size'];
        $fileInfo['sizetxt'] = sprintf('%.2f',$fileInfo['size']/1024).'kb';

        $thumInfo = $this->cutThum($fileInfo);
        if(empty($thumInfo)){
            return $this->_sysError[3];
        }
        $result['code'] = $thumInfo['code'];
        $result['msg'] = $thumInfo['msg'];
        $result['data'] = $thumInfo['data'];
        return $result;
    }

    /**
     * Notes:创建缩略图-根据本地图片路径
     * User: ZhuHaili
     * Date: 2022/11/7
     */
    private function localThum($param){
        if(!isset($param['local']) || !$param['local']){
            return $this->_sysError[1];
        }
        $res = $this->thumBase($param);
        if($res){
            return $res;
        }
        $this->_sysFileNewPath = $param['local'];
        $thumKeep = isset($param['thum_keep']) ? $param['thum_keep'] : 0;
        $this->_sysFileNewName = !$thumKeep ? $this->fileNameStr() : $this->getFileSuffix($param['local'], PATHINFO_FILENAME);
        $this->_sysSuffix = $this->getFileSuffix($param['local']);
        $fileInfo = $this->getFileInfo($param['local']);
        $fileInfo['width'];
        $fileInfo['height'];
        $thumInfo = $this->cutThum($fileInfo);
        if(empty($thumInfo)){
            return $this->_sysError[3];
        }
        $result['code'] = $thumInfo['code'];
        $result['msg'] = $thumInfo['msg'];
        $result['data'] = $thumInfo['data'];
        return $result;
    }

    /**
     * Notes: 生成缩略图
     * User: ZhuHaili
     * Date: 2020/4/10
     * @param $fileInfo
     * @return array|mixed
     */
    private function cutThum($fileInfo){
        if(!$this->_sysThumFlag){
            return array();
        }
        if(!$fileInfo['width'] || !$fileInfo['height']){
            return array();
        }
        $oldWidth = $fileInfo['width'];
        $oldHeight = $fileInfo['height'];
        $thumNewPath = $this->_sysThumPath.$this->_sysFileNewName.'.'.$this->_sysSuffix;
        // 根据标识分流
        $sysImgX = $sysImgY = 0;

        // 为5时智能定义裁剪类型
        if($this->_sysThumFlag == 5){
            $this->_sysThumFlag = $oldWidth > $oldHeight ? 2 : ($oldWidth < $oldHeight ? 3 : 1);
        }
        // 根据类型计算宽高
        if($this->_sysThumFlag == 2){ // 宽度固定高度自适应
            $newWidth = $this->_sysThumWidth;
            $newHeight = intval($newWidth)/intval($oldWidth)*intval($oldHeight); // 高等比缩放
        }else if($this->_sysThumFlag == 3){ // 高度固定宽度自适应
            $newHeight = $this->_sysThumHeight;
            $newWidth = intval($newHeight)/intval($oldHeight)*intval($oldWidth); // 高等比缩放
        }else if($this->_sysThumFlag == 4){ // 按中心点裁剪
            $newWidth = $this->_sysThumWidth;
            $newHeight = $this->_sysThumHeight;
            $sysImgX = ($oldWidth/2)-($newWidth/2);
            $sysImgY = ($oldHeight/2)-($newHeight/2);
            $oldWidth = $newWidth;
            $oldHeight = $newHeight;
        }else if($this->_sysThumFlag == 6){ // 宽度设置最大值，高度自适应
            $newWidth = $oldWidth > $this->_sysThumWidth ? $this->_sysThumWidth : $oldWidth;
            $newHeight = intval($newWidth)/intval($oldWidth)*intval($oldHeight); // 高等比缩放
        }else if($this->_sysThumFlag == 7){ // 高度设置最大值，宽度自适应
            $newHeight = $oldHeight > $this->_sysThumHeight ? $this->_sysThumHeight : $oldHeight;
            $newWidth = intval($newHeight)/intval($oldHeight)*intval($oldWidth); // 高等比缩放
        }else if($this->_sysThumFlag == 8){ // 不超过指定值按原值，超过按照设定最大值（宽高设置最大值）
            if($oldWidth > $oldHeight){
                $newWidth = $oldWidth > $this->_sysThumWidth ? $this->_sysThumWidth : $oldWidth;
                $newHeight = intval($newWidth)/intval($oldWidth)*intval($oldHeight); // 高等比缩放
            }else if($oldWidth < $oldHeight){
                $newHeight = $oldHeight > $this->_sysThumHeight ? $this->_sysThumHeight : $oldHeight;
                $newWidth = intval($newHeight)/intval($oldHeight)*intval($oldWidth); // 高等比缩放
            }else{
                $newWidth = $oldWidth > $this->_sysThumWidth ? $this->_sysThumWidth : $oldWidth;
                $newHeight = $oldHeight > $this->_sysThumHeight ? $this->_sysThumHeight : $oldHeight;
            }
        }else{ // 宽高固定压缩
            $newWidth = $this->_sysThumWidth;
            $newHeight = $this->_sysThumHeight;
		}

        // 根据图片类型分流
        if(in_array($this->_sysSuffix, array('JPG','jpg','jpe','jpeg','jpz'))){
            $image = imagecreatefromjpeg($this->_sysFileNewPath);
        }else if($this->_sysSuffix == 'png'){
            $image = imagecreatefrompng($this->_sysFileNewPath);
            if(str_replace('.', '', PHP_VERSION)>= 512){ //针对php版本大于5.12参数变化后的处理情况
                //$quality = 90;
            }
        }else if($this->_sysSuffix == 'gif'){
            $image = imagecreatefromgif($this->_sysFileNewPath);
        }else if($this->_sysSuffix == 'bmp') {
            $image = imagecreatefrombmp($this->_sysFileNewPath);
        }else if($this->_sysSuffix == 'wbmp'){
            $image = imagecreatefromwbmp($this->_sysFileNewPath);
        }else if($this->_sysSuffix == 'webp'){
            $image = imagecreatefromwebp($this->_sysFileNewPath);
        }

        // 是否取得图形
        if(!$image){
           return $this->_sysError[9];
        }

        // 新建一个w*y黑色图像
        //$thumb = imagecreatetruecolor ($newWidth, $newHeight);

        if($this->_sysSuffix == 'png'){
            // 透明
            imagesavealpha($image,true);//这里很重要;
            $thumb = imagecreatetruecolor($newWidth, $newHeight);
            imagealphablending($thumb,false);//这里很重要,意思是不合并颜色,直接用$img图像颜色替换,包括透明色;
            imagesavealpha($thumb,true);//这里很重要,意思是不要丢了$thumb图像的透明色;
            imagecopyresampled($thumb, $image,0,0,0,0,300,300,300,300);
            imagepng($thumb,$thumNewPath);
        }else{
            // 白色
            $thumb = imagecreatetruecolor ($newWidth, $newHeight);
            $white = imagecolorallocate($thumb,255,255,255);
            imagefilledrectangle($thumb,0,0,$newWidth, $newHeight, $white);
            imagecolortransparent($thumb, $white);
        }

        //图像中的一块矩形区域拷贝到另一个图像中
        if(function_exists('imagecopyresampled')){
            imagecopyresampled($thumb, $image, 0, 0, $sysImgX, $sysImgY, $newWidth, $newHeight, $oldWidth, $oldHeight);
        }else{
            imagecopyresized($thumb, $image, 0, 0, $sysImgX, $sysImgY, $newWidth, $newHeight, $oldWidth, $oldHeight);
        }
        //将图形输出到目标目录
        if(in_array($this->_sysSuffix, array('jpg','jpe','jpeg','jpz'))){
            imagejpeg($thumb, $thumNewPath, $this->_sysThumQuality);
        }else if($this->_sysSuffix == 'png'){
            imagepng($thumb, $thumNewPath, ($this->_sysThumQuality ? ($this->_sysThumQuality/10 > 9 ? 9 : $this->_sysThumQuality/10) : 9));
        }else if($this->_sysSuffix == 'gif'){
            imagegif($thumb, $thumNewPath, $this->_sysThumQuality);
        }else if($this->_sysSuffix == 'bmp') {
            imagebmp($thumb, $thumNewPath, $this->_sysThumQuality);
        }else if($this->_sysSuffix == 'wbmp') {
            imagewbmp($thumb, $thumNewPath, $this->_sysThumQuality);
        }else if($this->_sysSuffix == 'webp') {
            imagewebp($thumb, $thumNewPath, $this->_sysThumQuality);
        }

        //释放与 image 关联的内存
        imagedestroy($thumb);
        imagedestroy($image);

        $result =  $this->_sysError[0];
		$result['data']['thum_name'] = $this->_sysFileNewName.'.'.$this->_sysSuffix;
        $result['data']['thum_path'] = $thumNewPath;
        $result['data']['thum_width'] = $newWidth;
        $result['data']['thum_height'] = $newHeight;
        $result['data']['thum_size'] = filesize($thumNewPath);
        $result['data']['thum_sizetxt'] = sprintf('%.2f',$result['data']['thum_size']/1024).'kb';
        return $result;
    }

    /**
     * Notes: 文件验证
     * User: ZhuHaili
     * Date: 2020/4/10
     * @param $params
     * @return mixed
     */
    private function verifyFile($params){
        if(!isset($_FILES)){
            return $this->_sysError[1];
        }
        if(!isset($params['input']) || !$params['input']){
            return $this->_sysError[2];
        }
        $fName = $params['input'];
        $this->_sysFiles = $_FILES[$fName];
        if(!isset($this->_sysFiles['type']) || !isset($this->_sysFiles['size']) || !isset($this->_sysFiles['name'])){
            return $this->_sysError[3];
        }
    }

    /**
     * Notes: 参数赋值/验证
     * User: ZhuHaili
     * Date: 2020/4/10
     */
    private function verifyParam($params){
        if(isset($params['size']) && intval($params['size']) > 0){
            $this->_sysFileSize = intval($params['size']);
        }
        if(isset($params['type']) && is_string($params['type'])){
            $this->_sysFileType = strval($params['type']);
        }

        if(isset($params['file_vague']) && $params['file_vague']){
            $this->_sysFileVague = true;
        }
        if(isset($params['path']) && is_string($params['path'])){
            $result = $this->createPath($params['path']);
            if(!$result){
                return $this->_sysError[6];
            }
            $this->_sysFilePath = $params['path'];
        }
        if(isset($params['thum_path']) && is_string($params['thum_path'])){
            $result = $this->createPath($params['thum_path']);
            if(!$result){
                return $this->_sysError[7];
            }
            $this->_sysThumPath = $params['thum_path'];
        }
        if(isset($params['thum_flag']) && intval($params['thum_flag'])){
            $thum_flag = intval($params['thum_flag']);
            $thum_flag = $thum_flag > 6 ? 1 : $thum_flag;
            $this->_sysThumFlag = $thum_flag;
        }
        if(isset($params['thum_width']) && intval($params['thum_width'])){
            $this->_sysThumWidth = intval($params['thum_width']);
        }
        if(isset($params['thum_height']) && intval($params['thum_height'])){
            $this->_sysThumHeight = intval($params['thum_height']);
        }
        if(isset($params['thum_quality']) && intval($params['thum_quality'])){
            $this->_sysThumQuality = intval($params['thum_quality']);
        }
        return array();
	}

    /**
     * Notes: 创建文件路径
     * User: ZhuHaili
     * Date: 2020/4/10
     * @param $path
     * @return bool
     */
    public function createPath($path){
        $result = true;
        $pathBy = array_filter(explode('/',$path)); //数组去除空值
        $pathNo = '';
        $pathAll = '';
        foreach($pathBy as $v){
            if($v == '.'||$v == '..'){
                $pathNo = $pathNo.$v.'/';
            }else{
                $pathAll = $pathAll.$pathNo.$v.'/';
                if(!file_exists($pathAll)){
                    if(@!mkdir($pathAll)){
                        $result = false;
                    }
                }
                $pathNo = '';
            }
        }
        return $result;
    }

    /**
     * Notes: 获取文件后缀名
     * User: ZhuHaili
     * Date: 2020/4/10
     * @param $fileTmpName
     * @param string $fileTmpType
     * @return int|string
     */
    public function getFileSuffix($filePath, $type = PATHINFO_EXTENSION){
        $suf = @pathinfo($filePath, $type); // 文件后缀
        return $suf ? strtolower($suf) : 'JPG';
    }

    /**
     * Notes: 获取文件信息
     * User: ZhuHaili
     * Date: 2020/4/10
     * @param $filePath
     * @return mixed
     */
    public function getFileInfo($filePath){
        $imageData = @getimagesize($filePath);
        $res['width'] = isset($imageData[0]) ? $imageData[0] : 0;
        $res['height'] = isset($imageData[1]) ? $imageData[1] : 0;
        $res['size'] = filesize($filePath);
        $res['sizetxt'] = sprintf('%.2f',$res['size']/1024).'kb';
        return $res;
    }

    /**
     * Notes:文件名字
     * User: ZhuHaili
     * Date: 2022/3/30
     */
    private function fileNameStr(){
        return date('YmdHis').$this->msec().rand(100,999);
    }

    /**
     * Notes: 获取3位毫秒数
     * User: ZhuHaili
     * Date: 2020/4/10
     * @return string
     */
    public function msec(){
        list($usec, $sec) = explode(" ", microtime());
        $msec = round($usec*1000);
        return sprintf("%03d", $msec);
    }

    /**
     * Notes: 判断文件类型，文件类型获取失败时通过此方法打卡文件读取类型
     * User: ZhuHaili
     * Date: 2020/4/10
     * @param $fileTmpName
     * @param string $fileTmpType
     * @return int|string
     */
    public function getFileType(){
        $filehead = fopen($this->_sysFileNewPath,'r');
        $bin = fread($filehead, 2); //读取文件2字节
        fclose($filehead);
        $data = unpack('C2chars', $bin);
        $type_code = intval($data['chars1'].$data['chars2']);
        switch ($type_code) {
            case 7790:
                $fileType = 'exe';
                break;
            case 7784:
                $fileType = 'midi';
                break;
            case 8075:
                $fileType = 'zip';
                break;
            case 8297:
                $fileType = 'rar';
                break;
            case 255216:
                $fileType = 'jpg';
                break;
            case 7173:
                $fileType = 'gif';
                break;
            case 6677:
                $fileType = 'bmp';
                break;
            case 13780:
                $fileType = 'png';
                break;
            default:
                $fileType = '';
                break;
        }
        return $fileType;
    }

    /**
     * Notes: 错误码
     * User: ZhuHaili
     * Date: 2020/4/10
     * @return array
     */
	private function errorArr(){
        return array(
            array('code'=>'10000','msg'=>'文件上传成功', 'data'=>array()),
            array('code'=>'50000','msg'=>'没有获取到上传文件信息', 'data'=>array()),
            array('code'=>'40000','msg'=>'上传文件控件名不能为空', 'data'=>array()),
            array('code'=>'40001','msg'=>'上传文件信息错误', 'data'=>array()),
            array('code'=>'40002','msg'=>'文件过大超出设置最大值', 'data'=>array()),
            array('code'=>'40003','msg'=>'文件类型不支持', 'data'=>array()),
            array('code'=>'50001','msg'=>'文件路径创建失败', 'data'=>array()),
            array('code'=>'50002','msg'=>'缩略图路径创建失败', 'data'=>array()),
            array('code'=>'30000','msg'=>'文件写入失败', 'data'=>array()),
            array('code'=>'30001','msg'=>'缩略图生成失败', 'data'=>array()),
            array('code'=>'30002','msg'=>'上传文件不合法', 'data'=>array()),
        );
    }
}

/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////【示例】////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/*
header("Content-type: text/html; charset=utf-8");
//error_reporting(E_ALL ^ E_NOTICE);

//////////////////////////==【通用方式】==///////////////////////////////////////
// 第1步：引入文件上传类
//include 'UploadsFiles.php';
$data1 = '';
$data2 = '';
// 第2步：根据自己需求设置上传参数，以下参数作为参考：
//$params['base64'] = $data1;                   // 为base64上传时【必填】数组或字符串（单文件直接传一个）
//$params['base64'] = array($data1, $data2);    // 为base64上传时【必填】数组或字符串（多文件数组方式）
$params['input'] = 'file_name';                 // 二进制文件参数名，为$_FILE时【必填】字符串 支持多文件上传(file控件name属性的值，例如<input type="file" name="file_name">)
$params['path'] = './upload/';                  // 上传路径【选填】默认：./uploads/
$params['size'] = 1024*1024*2; // 2Mb           // 上传文件大小限制【选填】默认值2Mb
//$params['type'] = 'jpg|gif|png';              // 上传类型【选填】默认值为常用的文件格式(包含图片、文档、压缩包、视频等)等
$params['thum_flag'] = 1;                       // 缩略图生成【选填】默认值0，上传文件不是图片时设置无效；(0:不压缩,1:固定宽高,2:固定宽高自适应,3:固定高宽自适应,4:中心点裁剪,5:只能识别2和3,6:宽限制最大值高自适应,7:高限制最大值宽自适应,8:限制最大宽和最大高，其他值均为1)
$params['thum_width'] = 200;                    // 缩略图宽【选填】默认值100(即100px),上传文件不是图片时设置无效
$params['thum_height'] = 200;                   // 缩略图高【选填】默认值100(即100px),上传文件不是图片时设置无效
$params['thum_quality'] = 100;                  // 缩略图质量【选填】默认值100,上传文件不是图片时设置无效
$params['thum_path'] = './upload/thum/';        // 缩略图上传路径【选填】默认值‘./uploads/thum/’,上传文件不是图片时设置无效
//$params['file_vague'] = false;                // 无扩展名文件上传开关【选填】默认false; false:不支持，true支持,默认值参考文件上传类getFileType方法可以自行追加
//第3步：实例化文件上传类，并调用文件上传方法即可
$uploads = new UploadsFiles();
$result = $uploads->uploadFile($params);
// 第四步：获取返回值（返回的是数组格式，根据实际情况需要json可以自行转换，比如json_encode($result, 320)）
//echo '<pre>';
//print_r($result); // 打印出结果集查看数据结构

///////////////////////////////////==【生成缩略图上传】==//////////////////////////////
/// local、input、base64 三个参数选其一
//$params['local'] = $result['data']['path'];
$params2['local'] = 'E:\www\1.jpg';     //【必填】为本地图片路径时
//$params2['input'] = 'file_name';      //【必填】为FILE上传
//$params2['base64'] = $data1;          //【必填】为base64时
$params2['thum_keep'] = 1;              // 保持原名字一致(base64时不起作用)
$params2['thum_flag'] = 1;              // 图片压缩类型（0,1,2,3,4,5,6,7,8）→
//0:不压缩,1:固定宽高,2:固定宽高自适应,3:固定高宽自适应,4:中心点裁剪,5:只能识别2和3,6:宽限制最大值高自适应,7:高限制最大值宽自适应,8:限制最大宽和最大高，其他值均为1
$params2['thum_path'] = './upload/';    // 缩略图上传路径
$params2['thum_width'] = 50;            // 缩略图宽
$params2['thum_height'] = 50;           // 缩略图高
//$result = $uploads->createThum($params2);

/////////////////////获取返回值///////////////////////////////////////
echo '<pre>';
print_r($result); // 打印出结果集查看数据结构

/////////////////// 单文件数据结构 ///////////////////////////////////////*/
/*
Array
(
    [code] => 10000
    [msg] => 文件上传成功
    [data] => Array
        (
            [width] => 503
            [height] => 507
            [size] => 15226
            [sizetxt] => 14.87kb
            [name] => 20200424105347501.jpg
            [path] => ./upload/20200424105347501.jpg
            [type] => jpg
            [thum_name] => 20200424105347501.jpg
            [thum_path] => ./upload/thum/20200424105347501.jpg
            [thum_width] => 100
            [thum_height] => 100
            [thum_size] => 7944
            [thum_sizetxt] => 7.76kb
        )
)
/////////////////////////////////////// 多文件数据结构 ///////////////////////////////////////
Array
(
    [0] => Array
        (
            [code] => 10000
            [msg] => 文件上传成功
            [data] => Array
                (
                    [width] => 132
                    [height] => 157
                    [size] => 10885
                    [sizetxt] => 10.63kb
                    [name] => 2022091012185331271.png
                    [path] => ./log/2022091012185331271.png
                    [type] => png
                )
        )
    [1] => Array
        (
            [code] => 10000
            [msg] => 文件上传成功
            [data] => Array
                (
                    [width] => 108
                    [height] => 179
                    [size] => 9641
                    [sizetxt] => 9.42kb
                    [name] => 2022091012185331536.png
                    [path] => ./log/2022091012185331536.png
                    [type] => png
                )
        )
)
注意：传单文件时如果以数组的方式传入返回的结果集是多文件的结构
*/
/////////////////////////////////////////////////////////////////////////////////
